import './index.scss'
import { Card, Form, Input, Button, message } from 'antd'
import logo from '@/assets/logo.png'
import { useDispatch } from 'react-redux'
import { fetchLogin } from '@/store/modules/user'
import { useNavigate } from 'react-router-dom'

const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const onFinish = async (values) => {
    console.log(values)
    // 触发异步action fetchLogin
    try {
      // 等待 dispatch 执行完成
     await dispatch(fetchLogin(values)); 
      // 1. 跳转到首页
      navigate('/');
      // 2. 提示一下用户
      message.success('登录成功');
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请检查输入信息');
    }
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form onFinish={onFinish} validateTrigger="onBlur">
          {/* 邮箱输入 */}
            <Form.Item
              name="userEmail"
              rules={[
                {
                  required: true,
                  type: 'email',
                  message: '请输入正确的邮箱地址',
                },
              ]}
            >
              <Input size="large" placeholder="请输入邮箱" />
            </Form.Item>

            {/* 密码输入 */}
            <Form.Item
              name="userPassword"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
            >
              <Input.Password size="large" placeholder="请输入密码" />
            </Form.Item>

            {/* 验证码输入 */}
            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
            >
              <Input size="large" placeholder="请输入验证码" />
            </Form.Item>

            {/* 提交按钮 */}
            <Form.Item>
              <Button type="primary" htmlType="submit" size="large" block>
                登录
              </Button>
            </Form.Item>
          </Form>
      </Card>
    </div>
  )
}

export default Login